<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

use App\Models\Order;
use DB;
class OrderController extends Controller
{
    /*
	 * 订单管理
	 * */
	 
    protected function index(Request $request){
    	$address_username	= $request->input('address_username');
		$order_sn			= $request->input('order_sn');
		$starttime			= $request->input('starttime');
		$endtime			= $request->input('endtime');
		$pay_status			= $request->input('pay_status');
		$shipping_status	= $request->input('shipping_status');
		$order_status		= $request->input('order_status');
		DB::enableQueryLog();
    	$order_list = Order::
    		when($address_username,function($query) use ($address_username){
    			return $query->where('address_username',$address_username);
    		})
			->when($order_sn,function($query) use ($order_sn){
				return $query->where('order_sn',$order_sn);
			})
			->when($pay_status,function($query) use ($pay_status){
				return $query->where('pay_status',$pay_status);
			})
			->when($shipping_status,function($query) use ($shipping_status){
				return $query->where('shipping_status',$shipping_status);
			})
			->when($order_status,function($query) use ($order_status){
				return $query->where('order_status',$order_status);
			})
			->when($starttime,function($query) use ($starttime,$endtime){
				if(!$endtime){
					return $query->whereDate('created_at',$starttime);
				}else{
					return $query->whereRaw("date(created_at) between '$starttime' and '$endtime'");
				}
				
			})
    		->orderBy('order_id','desc')->paginate(15);
    	return view('admin.order.index',[
    		'order_list'	=> $order_list
    		]);
    }
	
	
	/*
	 * 发货设置
	 * */
	protected function setShippingStatus(Request $request){
		$order_id = $request->input('order_id');
		$status = $request->input('status');
		
		$order = Order::find($order_id);
		if($status==2 && $order->order_status==0){
			$order->order_status =1;//处理订单
		}
		$order->shipping_status = $status;
		switch ($order->shipping_status) {
			case '2':
				$order->shipping_time = date("Y-m-d H:i:s");
				break;
			case '3':
				$order->confirm_time = date("Y-m-d H:i:s");
				break;
		}
		if($order->save()){
			return response()->json([
				'code'	=> '00001',
				'msg'	=> '状态设置成功',
				'url'	=> ''
				]);					
		}else{
			return response()->json([
				'code'	=> '10001',
				'msg'	=> '状态设置失败',
				'url'	=> ''
				]);			
		}
		
	}
	
	
	/*
	 * 订单状态设置
	 * 
	 * */
	protected function setOrderStatus(Request $request){
		$order_id = $request->input('order_id');
		$status = $request->input('status');
		$order = Order::find($order_id);
		$order->order_status =$status;//处理订单
		if($order->save()){
			return response()->json([
				'code'	=> '00001',
				'msg'	=> '状态设置成功',
				'url'	=> ''
				]);			
		}else{
			return response()->json([
				'code'	=> '10001',
				'msg'	=> '状态设置失败',
				'url'	=> ''
				]);			
		}
		
	}
}
